<template>
  <div class="loginpage">
    <div class="l-h">
      <img class="img1" src="//chengguo-1309318813.cos.ap-beijing.myqcloud.com/uploads/zizhi/1733658423176%E9%A1%B5%E7%9C%89.png" alt="">
      <div class="l-h-r" @click="to('/')">
        <img src="//chengguo-1309318813.cos.ap-beijing.myqcloud.com/uploads/zizhi/1733658505979%E9%A6%96%E9%A1%B5%2C%E5%B1%8B%E5%AD%90%2C%E4%B8%BB%E9%A1%B5%2C%E6%88%BF%E5%AD%90.png" alt="">
        <div class="back">返回首页</div>
      </div>
    </div>

    <div class="l-c">
      <!-- 注册 -->
      <div class="post-c">
        <div class="post-head">
          <el-button type="primary" @click="to('/login')">
            已有账号？立即登录
            <img src="//chengguo-1309318813.cos.ap-beijing.myqcloud.com/uploads/zizhi/1733663172397%E8%BF%94%E5%9B%9E.png" alt="">
          </el-button>
        </div>
        <div class="post-head-t">
          小院研究生入驻登记
        </div>

        <el-steps style="max-width: 600px" :active="step" align-center>
          <el-step title="入驻登记" />
          <el-step title="入驻成功" />
        </el-steps>

        <div  class="post-stu">
          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="rules"
            class="demo-ruleForm"
            :size="formSize"
            status-icon
            v-if="step === stepEnum.step1"
          >
            <el-form-item required label="入驻小院时间" prop="checkInDate">
              <el-date-picker
                v-model="ruleForm.checkInDate"
                type="datetime"
                placeholder="请输入入驻小院时间"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="YYYY-MM-DD"
                style="width: 100%;"
              />
            </el-form-item>

            <el-form-item label="所在院校" prop="school">
              <el-input placeholder="请输入所在院校" v-model="ruleForm.school" />
            </el-form-item>

            <el-form-item label="所学专业" prop="speciality">
              <el-input placeholder="所学专业" v-model="ruleForm.speciality" />
            </el-form-item>

            <el-form-item label="所在年级" prop="grade">
              <el-input placeholder="请输入所在年级" v-model="ruleForm.grade" />
            </el-form-item>

            <el-form-item label="学号" prop="studentNumber">
              <el-input placeholder="请输入学号" v-model="ruleForm.studentNumber" />
            </el-form-item>

            <el-form-item label="导师姓名" prop="supervisor">
              <el-input placeholder="请输入导师姓名" v-model="ruleForm.supervisor" />
            </el-form-item>

            <el-form-item label="小院通信地址" prop="address">
              <el-input placeholder="请输入小院通信地址" v-model="ruleForm.address" />
            </el-form-item>

            <el-form-item required label="上传照片" prop="photo">
              <el-upload
              class="avatar-uploader"
              list-type="picture-card"
              :http-request="uploadFilePromise"
              action="#" 
              :limit="1"
              :on-remove="handleRemove"
              :file-list="fileList"
            > 
              <el-icon @click="uploadFilePromise(scope)"><Plus /></el-icon>
            </el-upload>
            </el-form-item>

            <el-form-item class="item-sb">
              <el-button class="s-btn" type="primary" @click="submitForm(ruleFormRef)">
                提交
              </el-button>
              <!-- <el-button @click="resetForm(ruleFormRef)">Reset</el-button> -->
            </el-form-item>
          </el-form>
          
          <div class="ruzhu-dj" v-if="step === stepEnum.step2">
            <img src="//chengguo-1309318813.cos.ap-beijing.myqcloud.com/uploads/zizhi/1733756056799%E5%AF%B9%E5%8B%BE_%E5%9D%97.png" alt="">
            <div>入驻成功</div>
            <!-- <el-button @click="to('/ruzhu')" class="e-b" type="primary">点击前往入驻登记</el-button> -->
          </div>

          <cropper :coverFile="coverFile" 
          @onClose="onClose"
          @cropperClick="cropperClick"
          ></cropper>

        </div>

      </div>

    </div>
  </div>
</template>  
<script setup>
	import { Search, User, Lock } from '@element-plus/icons-vue';
  import { useRouter } from 'vue-router';
  import { computed, reactive, ref } from 'vue'
  import { pageCourtyard, updatePostgraduate, } from '@/api/home';
  import encrypt from '@/utils/cryptoUtil';
  import { getTxCosCredential, saveQuestion } from '@/api/home'
  import COS from 'cos-js-sdk-v5'
  import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue';
  import { ElMessageBox } from 'element-plus';
  import cropper from './cropper.vue'

  import { useStore } from 'vuex'//导入createStore构造函数
	const store = useStore();
	const userinfo = computed(() => store?.state?.userinfo)
  const coverFile = ref('')

  console.log('0--userinfo',userinfo)
  const stsToken = ref({});
  const fileList = computed(() => {
    if(ruleForm.photo) {
      return [{
        id: '0',
        name: '1',
        url: ruleForm.photo
      }]
    }
    return []
  })

  const handleRemove = () => {
    fileList.value = [];
    ruleForm.photo = '';
  }

  const uploadFilePromise = (file) => {
    if(!file) return
    
    // dialogVisible.value = true;
    if(stsToken.value.credentials) {
      const cos = new COS({
        getAuthorization: function(option, callback) {
          callback({
            TmpSecretId: stsToken.value.credentials.tmpSecretId,
            TmpSecretKey: stsToken.value.credentials.tmpSecretKey,
            XCosSecurityToken: stsToken.value.credentials.sessionToken,
            ExpiredTime: stsToken.value.expiredTime
          })
        }
      })
		  uploadFile(cos,file.file, (path) => {
        coverFile.value = path;
      })
      return
    }

    getTxCosCredential().then(res=> {
      stsToken.value = res.data;
      const cos = new COS({
        getAuthorization: function(option, callback) {
          callback({
            TmpSecretId: stsToken.value.credentials.tmpSecretId,
            TmpSecretKey: stsToken.value.credentials.tmpSecretKey,
            XCosSecurityToken: stsToken.value.credentials.sessionToken,
            ExpiredTime: stsToken.value.expiredTime
          })
        }
      })
		  uploadFile(cos,file.file, (path) => {
        coverFile.value = path;
      })
    })
	}

  const uploadFile =  (cos, file, cb)=> {
    cos.putObject(
      {
        Bucket: stsToken.value.bucket,  // 存储桶名称
        Region: stsToken.value.region, // 地区
        Key:`/uploads/zizhi/${new Date().getTime()}${file.name}` , // 图片名称
        Body: file,
        onHashProgress: function (progressData) {
          console.log ('校验中', JSON.stringify (progressData));
        },
        onProgress: function (progressData) {
          console.log ('上传中', JSON.stringify (progressData));
        },
      },
      function (err, data) {
        if (err) {
          // this.error(file)
          return;
        }
        console.log('----data',data)
  

        if(data?.statusCode==200 && data?.Location) {
          const ll = `${location.protocol}//${data.Location}`
          if(cb) {
            cb(ll)
            return
          }
          _$.$message({type: 'success',message:'上传成功'})
          ruleForm.photo = ll;
          coverFile.value = '';
          console.log('----ll', ll)
          
        } else {
          _$.$message({type: 'success',message:'上传失败，请重新上传'})
        }

        // fileList.value = [{
        //   name: '1',
        //   url: `http://${data.Location}`
        // }]
      }
    );
	}

  const cropperClick = (file) => {
    console.log('---e',file)
    const cos = new COS({
      getAuthorization: function(option, callback) {
        callback({
          TmpSecretId: stsToken.value.credentials.tmpSecretId,
          TmpSecretKey: stsToken.value.credentials.tmpSecretKey,
          XCosSecurityToken: stsToken.value.credentials.sessionToken,
          ExpiredTime: stsToken.value.expiredTime
        })
      }
    })
    uploadFile(cos,file)
  }

  const onClose = () => {
    coverFile.value = ''
  }

  const stepEnum = {
    step0: 0,
    step1: 1,
    step2: 2,
  }
  const step = ref(stepEnum.step1); // 2
  const router = useRouter();

  const formSize = ref('default')
  const ruleFormRef = ref()
  const ruleForm = reactive({
    checkInDate: '',
    school:'',
    speciality:'',
    grade: '',
    studentNumber: '',
    address: '',
    photo:'',
    supervisor: '',
    postgraduateId: '',
  })

   // 科技小院
  const yards = ref([]);
  const getPageCourtyard =  async(courtyardType) => {
    const params = {
      params: {
        status: true,
        // courtyardType: '',
      },
      page: {
        pageSize: 10000,
        pageNum: 0,
      }
    }
    const ret = await pageCourtyard(params)
    yards.value = ret?.data?.list || [];
  }
  getPageCourtyard('');

  const rules = reactive({
    checkInDate: [
    { 
        required: true, 
        message: '请输入时间', 
        trigger: 'blur' 
      },
    ],

    photo: [
      { required: true, 
        message: '请上传图片', 
       },
    ],

  })

  const submitForm = async (formEl) => {
    console.log('submit!', userinfo.value)
    if (!formEl) return
    await formEl.validate(async(valid, fields) => {
      if (valid) {
        console.log('submit!', userinfo.value)
        const params = {
            ...ruleForm,
            postgraduateId: userinfo.value?.uid
          }
        const ret = await updatePostgraduate({
          params
        })
        console.log('rettt', ret)
        if(ret?.code == '200') {
          _$.$message({type: 'success',message:  '入驻成功'})
          setTimeout(() => {
            window.location.href = '/'
          }, 300);
        } 
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
  }



  const to = (path) => {
    router.push(path)
  }

</script>
<style lang="scss" scoped>
.loginpage {
  width: 100%;
  height: 100%;
  flex: 1;
  background: url(//chengguo-1309318813.cos.ap-beijing.myqcloud.com/uploads/zizhi/1733657881212%E5%9B%BE%E5%B1%82%201.png) no-repeat center center / cover;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .l-h {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 60px 10% 0;
    align-items: center;
      .img1 {
        width: 800px;
      }
    .l-h-r {
      display: flex;
      align-items: flex-end;
      color: #fff;
      font-size: 24px;
      cursor: pointer;
      align-items: flex-end;
      height: 45px;
      img {
        margin-right: 10px;
      }
      .back {
        align-self: flex-end;
        margin-bottom: -5px;
      }
    }
  }

  .l-c {
    display: flex;
    flex: 1;
    color: #fff;
    font-size: 30px;
    font-weight: normal;
    padding: 0 10%;
    width: 100%;
    .choose-type {
      padding-top: 120px;
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      .c-t {
        color: #fff;
        font-size: 55px;
        margin-bottom: 40px;
      }
      .c-content {
        width: 70%;
        height: 600px;
        background-color: #0a9c55;
        border-radius: 40px;
        overflow: hidden;
        display: flex;
        .content-btn {
          flex: 1;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          border-right: 1px solid rgb(255, 255, 255, 0.4);
          &:last-child {
            border-right: 0 none;
          }
          flex-direction: column;
          img {
            width: 200px;
          }
          .el-button {
            width: 300px;
            height: 70px;
            font-size: 26px;
            margin-top: 40px;
            &:hover {
              background-color: #0a9c55
            }
          }
        }
      }
    }

    .post-c {
      background: #fff;
      width: 100%;
      margin-top: 30px;
      border-radius: 30px;
      .post-head {
        color: #fff;
        display: flex;
        justify-content: flex-end;
        padding: 40px 30px;
        .el-button {
          height: 50px;
        }
        img {
          width: 30px;
          margin-left: 10px;
        }
      }
      .post-head-t {
        color: #0cbf68;
        width: 100%;
        text-align: center;
        font-size: 35px;
      }
      .el-steps {
        margin: 0 auto;
        padding-top: 60px;
        :deep(.is-finish) {
          color: #333;
          .el-step__icon {
            background-color: #0cbf68;
            color: #fff;
            border: 0 none;
          }
          .el-step__line {
            top: 23px;
          }
        }
        :deep(.is-process) {
          .el-step__icon {
            background-color: #f6bf58;
            color: #fff;
            border: 0 none;
          }
      
        }
      }
      .demo-ruleForm {
        margin: 0 auto;
        padding-top: 60px;
        width: 1000px;
        :deep(.el-form-item) {
          margin-bottom: 40px;
          .el-form-item__label {
            margin-right: 50px;
            color: #333;
            width: 200px;
          }
          .el-form-item__content {
            .el-input {
              height: 60px;
              .el-input__wrapper {
                background-color: #eef8f3;
              }
            }
            .el-select {
              .el-select__wrapper {
                background-color: #eef8f3;
                height: 60px;
              }
            }
          }
          .el-input-group__append {
            button.el-button {
              background-color: #0a9c55;
              color: #fff;
              height: 100%;
            }
          }
          &.item-sb {
            .el-form-item__content {
              justify-content: flex-end;
            }
            .s-btn {
              height: 70px;
              color: #fff;
              width: 75%;
           }
          }
        
        }
      }
      .ruzhu-dj {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding-top: 150px;
        color: #000;
        font-size: 28px;
        img {
          width: 150px;
          margin-bottom: 20px;
        }
        .e-b {
          margin-top: 80px;
        }
      }
    }
  }

  :deep(.demo-ruleForm) {
    input, textarea {
      font-size: 20px;
    }
    .el-form-item__label {
      font-size: 18px;
    }
    .el-form-item__error {
      font-size: 20px;
    }
    .avatar-uploader {
      
    .el-upload, .el-upload-list {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
      width: 178px;
      height: 178px;
      margin: 0;
      .el-upload-list__item {
        width: 178px !important;
        height: 178px !important;
        margin: 0;
      }
    .el-upload-list__item-thumbnail {
        object-fit: cover !important;
      }
    }
    .el-upload-list__item-preview {
      display: none;
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    }
  }

}
</style>